<template>
	<view class="tab-content">
		<view class=" uni-common-mt">
			<uni-segmented-control :current="current" :values="tabBars" style-type="button"
				active-color="#18bc9c" @clickItem="onClickItem" />
		</view>

		<view v-show="current === 0">
			<tableHead :poorder="poorder" prestr="MOUT" :order_type="2" ref="thead"></tableHead>
		</view>

		<view v-show="current === 1">
			<scroll-view scroll-y="true" style="height: 80vh;">
				<view class="form_list">
					<showMaterialList :dataArr="porderItem" :orderType="2" flag='out' :checkKc="true" :showShelves="false" :showShelvesName="true" ref="showMaterialList"></showMaterialList>
				</view>
			</scroll-view>
			<view class="swiper-button">
				<button @click="$refs.thead.toSerial()">选择源单</button>
				<button @click="toMaterialList">添加物料</button>
				<button @click="checkOrder">完成</button>
			</view>
		</view>
	</view>
</template>

<script>
	import tableHead from "@/component/table-head.vue"
	import showMaterialList from "@/component/show-material-list.vue"
	import {
		uniSegmentedControl
	} from '@dcloudio/uni-ui'
	export default {
		components: {
			uniSegmentedControl,tableHead,showMaterialList
		},
		data() {
			return {
				current: 1,
				/* 选中标签栏的序列,默认显示第一个 */
				tabBars: ['表头', '表体'],
				
				poorder: {}, //源单对象
				porderItem: [],//动态变化的数组
				porderItemOld:[],//最初的明细，用于判断比较上面变化的数组
				
				user:uni.getStorageSync('user')
			}
		},
		computed: {},
		watch:{},
		onLoad(options) { 
			this.$Func.setBarTitle('生产领料出库')//拣货
			//初始化
			setTimeout(()=>{
				this.$refs.thead.init() //初始化
			},500)
			
			/* 监听物料选择列表 */
			uni.$off("getMarr")
			uni.$on("getMarr", (value) => {
				this.setMaterial(value)
			})
		},
		destroyed:function(){
			uni.$off("getMarr")
			uni.$off("getAppmaterial")
		},
		onShow() {
			//监听选择源单
			uni.$off("getAppmaterial")
			uni.$once("getAppmaterial", (value) => {
				// if(value.fclose==1){
				// 	this.$Api.msg('该单号已被引用','error')
				// }else{
				this.poorder = value
				this.$refs.thead.remark = value.remark
				
				uni.showLoading();
				this.$Db.selectTableData('outask', 'pcode', value.pcode).then(res => {
					this.porderItem = []//先清空之前
					this.porderItemOld = []//先清空之前old
					res.forEach((arr) => {
						arr.real_quantity = this.$Func.decimalPattern(arr.quantity - arr.commit_quantity) //实出
						arr.quantity = arr.real_quantity  //应出
						arr.real_store_quantity = Number(arr.real_quantity/arr.fCoefficient)//常用数量
						
						arr.shelves_id = 0 //初始化为0
						arr.shelves_name = ''
						
						if(arr.seorder_batch_shelves!=''){
							//订单自带批号
							let temp = arr.seorder_batch_shelves.split('_')
							arr.shelves_id = temp[0]
							arr.shelves_name = temp[1]
						}else{
							if(arr.kc_tj_cBatch!=''){
								//有推荐，用推荐
								let temp = arr.kc_tj_cBatch.split('_')
								arr.shelves_id = temp[0]
								arr.shelves_name = temp[1]
								arr.cBatch = temp[2]
							}
						}
						
						if(arr.quantity>0){
							this.porderItem.push(arr)
							this.porderItemOld.push(arr)
						}
					});
					uni.hideLoading();
				})
				//}
			})
		},
		methods: {
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
			//选择物料
			toMaterialList() {
				if(JSON.stringify(this.poorder) == "{}"){
					this.$Api.msg('请先选择源单','error');
					return ;
				}
				
				this.globalData.toSecPage = 'inventory' //进入二级页
			 	uni.navigateTo({
			 		url: '/pages/inventory/index?flag=add'
			 	})
			},
			//核实物料
			async checkOrder() {
				if (JSON.stringify(this.poorder) == "{}"||this.porderItem.length == 0) {
					this.$Api.msg('请选择源单','error');
					return;
				}
				
				let check_total = 0 //总数不能为0
				let overflag = false
				let billentry = []
				let newPorderItem = []
					
				for(let i in this.porderItem){
					let citem = this.porderItem[i]
					let real_quantity = parseFloat(citem.real_quantity)
					let quantity = parseFloat(citem.quantity)
					let kc_quantity = parseFloat(citem.kc_quantity)
					let commit_quantity = parseFloat(citem.commit_quantity)
					
					if(real_quantity == 0 || isNaN(real_quantity)){
						continue
					}
					
					check_total += real_quantity //累加总数 
					
					//实收数量超过应收提示
					if(real_quantity>quantity){
						this.$Api.msg(citem.inv_name+'实出数量大于应出数');
						return ;
					}
					
					if(citem.shelves_id == ''||citem.shelves_id == 0) {
						this.$Api.msg(citem.inv_name+'目标库区为空,请重选批号')
						// this.$Api.msg(citem.inv_name+'目标货架、库区不能为空')
						// setTimeout(()=>{
						// 	this.$refs.showMaterialList.toGetShelves(i,0)
						// },1000)
						return
					}
					
					if(real_quantity>kc_quantity){
						this.$Api.msg(citem.inv_name+'实出数量大于库存数')
						return
					}
					
					//单据表体添加
					billentry.push({
						'FBillNo':this.$refs.thead.FBillNo,
						'auto_id':citem.auto_id,
						'row_id':citem.row_id,
						'local_row_id':i,
						'inv_number':citem.inv_number,
						'inv_name':citem.inv_name,
						'inv_specification':citem.inv_specification,
						'inv_attributes':citem.inv_attributes,
						'inv_unit':citem.unit_name,
						'inv_unit_code':citem.unit_code,
						'store_unit':citem.store_unit,
						'store_unit_code':citem.store_unit_code,
						'fqty':real_quantity,
						'fauxqty':citem.real_store_quantity,
						'cBatch':citem.cBatch,
						'shelves_id':citem.shelves_id,
						'shelves_name':citem.shelves_name,
						'shelves_type':citem.shelves_type,
						'b_remark':''
					})
					
					//应出数
					citem.no_quantity = this.$Func.decimalPattern(quantity - commit_quantity)
					newPorderItem.push(citem)
				}
				
				if(!check_total||!billentry.length||isNaN(check_total)){
					this.$Api.msg("出库数量全为0")
					return 
				}
				
				/* if(this.$refs.thead.to_shelves_id==''||isNaN(this.$refs.thead.to_shelves_id)){
					this.$Api.msg("请选择暂存路径")
					this.current = 0
					return 
				} */
				
				check_total = this.$Func.decimalPattern(check_total)//小数点后4位
				
				//合并同个row_id的数量
				let mergeArr = this.$Func.arraySameKeySum(newPorderItem)
				
				let flag = true
				if(mergeArr.length!=newPorderItem.length){
					//合并后的数组长度不一致，则进行数量判断
					mergeArr.find(citem=>{
						let findItem = newPorderItem.find(item => citem.row_id==item.row_id&&citem.real_quantity>item.no_quantity)
						if(findItem!=undefined){
							//存在超过数量
							this.$Api.msg(findItem.inv_name+"实出总数超过应出数,请核实")
							flag = false
							return
						}
					})
				}
				
				//表头
				let bill = {//准备表头数据
					'auto_id':this.poorder.auto_id,
					'source_code':this.poorder.pcode,
					'order_type':2,//材料清单
					'FBillNo':this.$refs.thead.FBillNo,
					'FDate':this.$refs.thead.FDateVal,
					'a_remark':this.$refs.thead.remark,
					'stock_id':this.$refs.thead.stock_id,
					//'to_shelves_id':0,//this.$refs.thead.to_shelves_id,
					//'to_shelves_name':this.$refs.thead.to_shelves_name,
					'status':1,
					'syn_status':0,
					'total_qty':check_total,
					'factory_code':this.poorder.cdepcode,
					'factory_name':this.poorder.cdepname,
					'userid':this.user.userid,
					'create_date':this.$Func.getDateTime('today','Y-m-d')
				}
				
				//判断是否存在重复记录 -- 同个货架，同个物料，拣货多次
				if(flag){
					let msg = this.$Func.checkSameShelvesInvOut(newPorderItem,'string')
					if(msg!=''){
						this.$Api.msg(msg)
						return
					}else{
						//新增记录
						this.addOrder(bill,billentry)
					}
				}
			},
			//设置额外物料
			async setMaterial(value){
				if(JSON.stringify(this.poorder) == "{}"){
					this.$Api.msg('请先选择源单','error')
					return
				}
			
				var eleOld  = this.porderItemOld.find(ele => ele.inv_number == value.number)
				if(eleOld == undefined){
					this.$Api.msg('材料清单不存在该物料')
					return 
				}else{
					// 或者使用Object.assign()方法创建一个新对象
					let eleNew = Object.assign({}, eleOld);
					eleNew.quantity = this.$Func.decimalPattern(eleOld.quantity - eleOld.commit_quantity) //应出按原物料数
					eleNew.real_quantity = 0//eleNew.quantity //额外添加的，实出先默认0
					eleNew.cBatch = ''
					eleNew.shelves_id = 0
					eleNew.shelves_name = ''
					
					this.porderItem.push(eleNew)
					this.$Api.msg('添加成功','success');
				}
			},
			//完成
			async addOrder(bill,billentry){
				uni.showLoading({mask:true})
				this.$Db.addOrder(2,bill,billentry).then(res=>{
					this.$Api.msg('添加成功','success')
					this.reset()
					uni.hideLoading();
				}).catch(err=>{
					this.$Api.msg('添加失败','error')
					this.$Db.addlog('添加材料清单出库',err)
					uni.hideLoading();
				})
			},
			//重置表单
			reset() {
				//日期重置
				this.poorder = {}
				this.porderItem = []
				this.$set(this.poorder, 'pcode', ''); // 清空对象属性
				this.$set(this.poorder, 'cdepname', ''); // 清空对象属性
				this.$refs.thead.reset() //初始化
			},
		}
	}
</script>
<style lang="scss">
</style>